/**
 * 
 */
package info.niwota.profile.ac;

import info.niwota.profile.R;
import info.niwota.profile.WebViewActivity;
import info.niwota.profile.client.HttpClient;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class AccountListActivity extends ListActivity {
	
	private static final String WEB_PROFILE_URI = HttpClient.BASE_URL
			+ "profile";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AccountManager ac = AccountManager.get(this);

		Account[] accounts = ac.getAccounts();
		// ac.getAccountsByType("com.google");

		if (accounts == null || accounts.length == 0) {
			// no accounts?
			doCreateAccount();
			finish();
		} else {
			String[] list = new String[accounts.length];
			for (int i = 0; i < accounts.length; i++) {
				list[i] = accounts[i].name;
			}
			setListAdapter(new ArrayAdapter<String>(this,
					R.layout.account_list_item, list));
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int pos, long id) {
//		Account ac = (Account) getListView().getItemAtPosition(pos);
//		doListProfile(ac.name);
		
		String user = (String) getListView().getItemAtPosition(pos);
		doListProfile(user);
	}

	private void doListProfile(String user) {
		try {
			Intent i = new Intent(this, WebViewActivity.class);
			Uri uri = Uri.parse(WEB_PROFILE_URI).buildUpon()
					.appendQueryParameter("user", user).build();
			i.setData(uri);
			startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		finish();
	}

	private void doCreateAccount() {
		try {
			Intent i = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
			startActivity(i);
		} catch (Error e) {
			e.printStackTrace();
		}
	}
}